//
//  ListViewController.m
//  Emoticon
//
//  Created by ytkjs2 on 2020/3/30.
//  Copyright © 2020 ytk. All rights reserved.
//

#import "ListViewController.h"
#import "ListViewCell.h"

@interface ListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong)NSMutableArray * dataSource;

@property (nonatomic, assign)int page;

@end

@implementation ListViewController

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view from its nib.
    [self.listCollectView registerNib:[UINib nibWithNibName:@"ListViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ListViewCell"];
    
    __weak typeof(self)weakSelf = self;
    
    self.listCollectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        for (int i = 0; i < 3; i ++) {
            [PictureData getRequestWithServiceUrl:Main_PicList_URL parameters:@{@"cate_id":@(self.cate_id),@"page":@(1 + i)} success:^(id  _Nonnull responseObject) {
                NSArray * arr = [responseObject objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    PicModel * model1 = [PicModel mj_objectWithKeyValues:dic];
                    [weakSelf.dataSource addObject:model1];
                }
                
                weakSelf.page = 1 + i;
//                if (weakSelf.dataSource.count == 45) {
                    [weakSelf.listCollectView reloadData];
                    [weakSelf.listCollectView.mj_header endRefreshing];
//                }
            } failure:^(NSError * _Nonnull error) {
                [weakSelf.listCollectView.mj_header endRefreshing];
            }];
        }
    }];
    [self.listCollectView.mj_header beginRefreshing];
    
    
    self.listCollectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        weakSelf.page ++;
        
        [PictureData getRequestWithServiceUrl:Main_PicList_URL parameters:@{@"cate_id":@(self.cate_id),@"page":@(weakSelf.page)} success:^(id  _Nonnull responseObject) {
            NSArray * arr = [responseObject objectForKey:@"data"];
            for (NSDictionary * dic in arr) {
                PicModel * model1 = [PicModel mj_objectWithKeyValues:dic];
                [weakSelf.dataSource addObject:model1];
            }

            [weakSelf.listCollectView reloadData];
            [weakSelf.listCollectView.mj_footer endRefreshing];
        } failure:^(NSError * _Nonnull error) {
             [weakSelf.listCollectView.mj_footer endRefreshing];
        }];
    }];
    [self.listCollectView.mj_footer beginRefreshing];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ListViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ListViewCell" forIndexPath:indexPath];
    
    PicModel * model = _dataSource[indexPath.item];
    
    NSString * imgUrl = @"";
    imgUrl = [model.image stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    uint8_t c;
    NSData * imgData = [self imageDataFromDiskCacheWithKey:imgUrl];
    [imgData getBytes:&c length:1];
    //判断动图
    if (c == 0x47) {
        cell.IMG.hidden = YES;
        cell.GIF_IMG.hidden = NO;

        NSURL *url = [NSURL URLWithString:imgUrl];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {

            [[[SDWebImageManager sharedManager] imageCache] storeImage:image
                                                             imageData:nil
                                                                forKey:url.absoluteString
                                                                toDisk:NO
                                                            completion:nil];

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                if (data != nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self animatedImageView:cell.GIF_IMG
                                           data:data];
                    });
                }
            });

        }];
    }
    else
        [cell.IMG sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"icon_placeholderImage"]];
    
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 6.5;//上下行
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 6.5;//行距
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(6.5, 12, 6.4, 12 );//分别为上、左、下、右
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = (rScreenWidth - 61)/4;
    
    return CGSizeMake(width,width);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicModel * model = _dataSource[indexPath.item];
    DownloadViewController * downloadVC = [[DownloadViewController alloc]initWithNibName:@"DownloadViewController" bundle:nil];
    downloadVC.dataSource = [_dataSource mutableCopy];
    downloadVC.picIndex = indexPath.item;
    [self.navigationController pushViewController:downloadVC animated:YES];
}


- (void)animatedImageView:(FLAnimatedImageView *)imageView data:(NSData *)data {
    
    FLAnimatedImage *gifImage = [FLAnimatedImage animatedImageWithGIFData:data];
    imageView.animatedImage   = gifImage;
}

- (NSData *)imageDataFromDiskCacheWithKey:(NSString *)key {
    
    NSString *path = [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:key];
    return [NSData dataWithContentsOfFile:path];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
